<template>
    <Layout>
        <Form ref="form1" :model="form1" :label-width="120">
            <Row class="query-form">
                <Col span="8">
                    <FormItem label="二级集团：">
                        <two-level-org org-code class="query-form-el" v-model="form1.twoLevelOrgCode" />
                    </FormItem>
                </Col>
                <Col span="8">
                    <FormItem label="上报单位：">
                        <Input type="text" v-model="form1.orgName"></Input>
                    </FormItem>
                </Col>
                <Col span="8" v-if="!switchFlag" >
                    <Button @click="switchQuery(true)" class="ivu-btn-switch" type="text">展开∨</Button>
                    <Button @click="reset" class="ivu-btn-reset">重置</Button>
                    <Button icon="md-search" class="ivu-btn-query" @click="query()">查询</Button>
                </Col>
                <Col span="8" v-else>
                    <FormItem label="事故类别：">
                        <Select v-model="form1.accTypeId"  >
                            <Option v-for="item in dictMap.typeList" :value="item.codingCodeId" :key="item.codingCodeId">{{  item.codingName  }}</Option>
                        </Select>
                    </FormItem>
                </Col>
            </Row>
            <Row v-show="switchFlag" class="query-form">
                <Col span="8">
                    <FormItem label="事故名称：">
                        <Input type="text" v-model="form1.sartName"></Input>
                    </FormItem>
                </Col>
                <!--<Col span="8">-->
                    <!--<FormItem label="就业类型：">-->
                        <!--<Select v-model="memberships" multiple  :max-tag-count="2">-->
                            <!--<Option v-for="item in membershipList" :value="item.codingCodeId" :key="item.codingCodeId">{{item.codingName}}</Option>-->
                        <!--</Select>-->
                    <!--</FormItem>-->
                <!--</Col>-->
                <Col span="8" offset="8">
                    <Button @click="switchQuery(false)" class="ivu-btn-switch" type="text">收起∧</Button>
                    <Button @click="reset" class="ivu-btn-reset">重置</Button>
                    <Button class="ivu-btn-query" icon="md-search" @click="query()">查询</Button>
                </Col>
            </Row>
            <Row class="query-form">
                <Col span="24">
                    <Button size="large" class="ivu-btn-add" icon="md-add" @click="addInfo">新增</Button>
                    <download-button :api="exportUrl" :queryForm='form1' />
                </Col>
            </Row>
        </Form>
        <Table ref='table' :height="tableHeight" :loading="loading" size="small" class="table" no-data-text="没有查询到相关数据!"
                 show-summary :summary-method="(data) => this.gAmountTo(data,['damage'])" 
               highlight-row stripe border :columns="columns1" width="100%" :data="dataTable">
        </Table>
        <Row style="margin-right:10px;">
            <Col span="24">
                <Page :total="pagedata.total" :page-size="pagedata.pageSize" @on-change="pageChange"
                      style="float: right" @on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray"
                      show-total show-sizer show-elevator/>
            </Col>
        </Row>

        <Modal :transfer=false :mask-closable="false" v-model="model1" :width=900  :styles="{height:'600px'}" :title="add?'安全事故续报新增':'安全事故续报修改'" class-name='limit-height-dialog'
               @on-cancel="onCancel">
                <Form ref='InputData' :model="InputData" :rules="ruleCustom" label-position="top">
                    <Row>
                        <Col span='11'>
                            <FormItem label="事故名称：" prop="briefId">
                                <Input v-model="InputData.sartName" placeholder="请选择事故名称" :readonly="true">
                                <Button slot="append" @click="openForSelect" icon="ios-search"></Button>
                                </Input>
                            </FormItem>
                        </Col>
                        <Col span='11' offset="1">
                            <FormItem label="事故类别：" prop="accTypeId">
                                <Input v-model="InputData.accTypeName" placeholder="请选择事故名称" :readonly="true"/>
                                <Input v-show="false" v-model="InputData.accTypeId" placeholder="请选择事故名称" :readonly="true"/>
                            </FormItem>
                        </Col>
                    </Row>
                        <Row>
                            <Col span='11'>
                                <FormItem label="直接经济损失估计(万元)：" prop="damage">
                              <!--      <Input v-model="InputData.damage"/>-->
                                    <InputNumber placeholder="请填写0-9数字包括小数" :min="0" type='text' v-model='InputData.damage' style="width: 100%"></InputNumber>
                                </FormItem>
                            </Col>
                            <Col span='11' offset="1">
                                <FormItem label="填报人：" prop="deptLeaderId">
                                    <Input v-show="false" v-model="InputData.deptLeaderId" type="text" readonly/>
                                    <Input v-model="InputData.deptLeaderName" type="text" readonly/>
                                </FormItem>
                            </Col>
                        </Row>
                    <Row v-if="InputData.sartName">
                        <Col span="23" class="query-form">
                            <p>事故伤亡人员信息</p>
                            <Table highlight-row stripe border style="margin-top:10px;margin-bottom: 10px" :max-height="350" :columns="columnsItem"
                                   :data="InputData.briefItems">
                            </Table>
                        </Col>
                    </Row>
					<Row>
					    <Col span='23'>
					        <FormItem label="直系亲属信息：" prop="relations">
					            <Input v-model="InputData.relations" type="textarea" :autosize="{minRows:2,maxRows:5}"/>
					        </FormItem>
					    </Col>
					</Row>
                    <Row>
                        <Col span='23'>
                            <FormItem label="属地政府调查情况：" >
                                <Input v-model="InputData.locationSurvey" type="textarea" :autosize="{minRows:2,maxRows:5}"/>
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span='23' >
                            <FormItem label="家属安抚情况：">
                                <Input v-model="InputData.appesase" type="textarea" :autosize="{minRows:2,maxRows:5}"/>
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span='23'>
                            <FormItem label="事故经过补充说明：" prop="additinalDesc">
                                <Input v-model="InputData.additinalDesc" type="textarea"
                                       :autosize="{minRows:2,maxRows:5}"/>
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span='23'>
                            <FormItem label='应急响应及救援情况：' prop="resRescue">
                                <Input v-model="InputData.resRescue" type="textarea" :autosize="{minRows:2,maxRows:5}"/>
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span='23'>
                            <FormItem label='备注：' prop="notes">
                                <Input v-model="InputData.notes" type="textarea" :autosize="{minRows:2,maxRows:5}"/>
                            </FormItem>
                        </Col>
                    </Row>
                </Form>
            <div slot="footer">
                <Button class='ivu-btn-save' :loading="buttonLoading" @click="submit('InputData')">确定</Button>
                <Button class='ivu-btn-cancel' @click="onCancel">取消</Button>
            </div>
        </Modal>

        <Modal :transfer=false v-model="model3" :width=850 title="安全事故续报详情" :styles="{height:'600px'}"  @on-cancel="onCancel" class-name='limit-height-dialog'>
            <Form :model="InputData" label-position="top">
                <div >
                    <Row style="line-height: 42px;margin-left: 20px">
                        <Col span='11'>
                            <span>事故名称：{{InputData.sartName}}</span>
                        </Col>
                      <Col span='11' offset="1">
                        <span>事故类别：{{InputData.accTypeName}}</span>
                      </Col>

                    </Row>
                    <!--<Row class="detail-background-clor">-->
                        <!--<Col span='11'>-->
                            <!--<span>填报人：{{InputData.deptLeaderName}}</span>-->
                        <!--</Col>-->
                        <!--<Col span='11' offset="1">-->
                            <!--<span>伤亡人员联系电话：{{InputData.contacterPhone}}</span>-->
                        <!--</Col>-->
                    <!--</Row>-->

                    <Row class="detail-background-clor" style="line-height: 42px;margin-left: 20px">
                        <Col span='11'>
                            <span>直接经济损失估计(万元)：{{InputData.damage}}</span>
                        </Col>
                      <!--<Col span='11' offset="1">-->
                        <!--<span>就业类型：{{InputData.employmentTypeName}}</span>-->
                      <!--</Col>-->
                    </Row>
                  <Row  style="line-height: 42px;margin-left: 20px">
                    <Col span='23'>
                      <span>上报单位：{{InputData.orgName}}</span>
                    </Col>
                  </Row>
                  <Row class="detail-background-clor" style="line-height: 42px;margin-left: 20px">
                      <Col span='11'>
                          <span>填报人：{{InputData.deptLeaderName}}</span>
                      </Col>
                    <Col span='11' offset="1">
                      <span>创建时间：{{this.formatDate(new Date(InputData.createDate),'yyyy-MM-dd')}}</span>
                    </Col>
                  </Row>
                    <Row >
                        <Col span="23" class="query-form" style="margin-left: 20px">
                            <p>事故伤亡人员信息</p>
                            <Table highlight-row stripe border style="margin-top:10px;margin-bottom: 10px" :max-height="350" :columns="columnsItem"
                                   :data="InputData.briefItems">
                            </Table>
                        </Col>
                    </Row>
                    <Row style="line-height: 42px;margin-left: 20px">
                        <Col span='23'>
                            <strong>直系亲属信息：</strong>
                            <span>{{InputData.relations}}</span>
                        </Col>
                    </Row>
                    <Row class="detail-background-clor" style="line-height: 42px;margin-left: 20px">
                        <Col span='23'>
                          <strong>属地政府调查情况：</strong>
                            <span>{{InputData.locationSurvey}}</span>
                        </Col>
                    </Row>
                    <Row style="line-height: 42px;margin-left: 20px">
                        <Col span='23' >
                          <strong>家属安抚情况：</strong>
                            <span>{{InputData.appesase}}</span>
                        </Col>
                    </Row>
                    <Row class="detail-background-clor" style="line-height: 42px;margin-left: 20px">
                        <Col span='23'>
                          <strong>事故经过补充说明：</strong>
                            <span>{{InputData.additinalDesc}}</span>
                        </Col>
                    </Row>
                    <Row  style="line-height: 42px;margin-left: 20px">
                        <Col span='23'>
                          <strong>应急响应及救援情况：</strong>
                            <span>{{InputData.resRescue}}</span>
                        </Col>
                    </Row>
                    <Row class="detail-background-clor" style="line-height: 42px;margin-left: 20px">
                        <Col span='23'>
                          <strong>备注：</strong>
                            <span>{{InputData.notes}}</span>
                        </Col>
                    </Row>


                </div>
            </Form>
            <div slot="footer">
                <Button class='ivu-btn-save' @click="onCancel">关闭</Button>
            </div>


        </Modal>
        <Modal title="事故简报" :transfer=false footer-hide v-model="briefingList"  :width=900>
            <FollowReportForSelect @getSelectData="getSelectData" >
            </FollowReportForSelect>
        </Modal>

    </Layout>
</template>

<script>
import {Api} from '../../../../api/index.js'
import {sessionStorage} from '../../../../common/cacheUtils.js';
import FollowReportForSelect from './followReportForSelect';
import cascaderDom from "../../../../components/cascader-dom.vue"

export default {
        name: "interestedPartiesBlack",
        components: {FollowReportForSelect, cascaderDom},
        data() {
            return {
				currentUser: JSON.parse(sessionStorage('userId').get('userId')),
                exportUrl: Api.follow+ '/export',
                briefingList: false,
                uploadList: [],
                tableHeight: '',
                loading: false,
                form1: {},
                sexList: [
                    {
                        value: '0',
                        text: '男'
                    },
                    {
                        value: '1',
                        text: '女'
                    }
                ],
                pageSizeArray: [10, 20, 50],
                pagedata: {
                    total: 0,
                    pageSize: 10,
                    currentPage: 1,
                },
                dataTable: [],
                ruleCustom: {
                    employmentType: [{
                        message: '  ',
                        required: true,
                        trigger: 'change'
                    }],
                    locationSurvey: [{
                        message: '  ',
                        required: true,
                        trigger: 'change'
                    }],
                    appesase: [{
                        message: '  ',
                        required: true,
                        trigger: 'change'
                    }],
                    briefId: [{
                        validator: (rule, value, callback) => {
                            if (value == null || value == '' || value == undefined) {
                                callback(' ')
                            } else {
                                callback()
                            }
                        },
                        required: true,
                        trigger: 'change'
                    }],
                    deptLeaderId: [{
                        validator: (rule, value, callback) => {
                            if (value == null || value == '' || value == undefined) {
                                callback(' ')
                            } else {
                                callback()
                            }
                        },
                        required: true,
                        trigger: 'change'
                    }],
                    injuryLevelName: [{
                        validator: (rule, value, callback) => {
                            if (this.InputData.injuryLevelName == null || this.InputData.injuryLevelName == '' || this.InputData.injuryLevelName == undefined) {
                                callback(' ')
                            } else {
                                callback()
                            }
                        },
                        required: true,
                        trigger: 'change'
                    }],
                    contacterPhone: [{
                        validator: (rule, value, callback) => {
                            if (!(/^1[3456789]\d{9}$/.test(value))) {
                                callback(' ');
                                //this.$Message.error("请填写有效的的手机号")
                            } else {
                                callback()
                            }
                        },
                        required: true,
                        trigger: 'blur'
                    }],
                    damage: [{
                        validator: (rule, value, callback) => {
                            if (!(/^(([^0][0-9]+|0)\.([0-9]{1,8})$)|^(([^0][0-9]+|0)$)|^(([1-9]+)\.([0-9]{1,8})$)|^(([1-9]+)$)/.test(value))) {
                                callback(' ');
                            } else {
                                callback()
                            }
                        },
                        message:'请填写0-9数字包括小数',
                        required: true,
                        trigger: 'blur'
                    }],
                },
                columns1: [
                    {
                        title: "序号",
                        width: 80,
                        align: "center",
                        fixed: 'left',
                        render: (h, params) => {
                            if(params.index == 0) return h('span', "汇总");
                            return h('span', params.index -1 + (this.pagedata.currentPage - 1) * this.pagedata.pageSize + 1);
                        }
                    },
                    {title: '事故名称', align: 'center', key: 'sartName', minWidth: 120,},
                    // {title: '上报单位', align: 'center', key: 'orgName',minWidth: 120,},
                    {title: '事故单位', align: 'center', key: 'reportOrgName', minWidth: 150, tooltip: true},
                    {title: '事故类别', align: 'center', key: 'accTypeName', minWidth: 100,},
                    // {title: '伤害程度', align: 'center', key: 'injuryLevelName',},
                    // {title: '就业类型', align: 'center', key: 'employmentTypeName',},
                    {title: '属地政府调查情况', align: 'center', key: 'locationSurvey',minWidth: 120, tooltip: true},
                    {title: '家属安抚情况', align: 'center', key: 'appesase', minWidth: 120,tooltip: true},
                    {title: '直接经济损失(万元)', align: 'center', key: 'damage',minWidth: 100,},
                    {
                        title: '操作',
                        key: 'action',
                        fixed: 'right',
                        width: 180,
                        align: 'center',
                        render: (h, params) => {
                            if (params.row.fReportId === '-1') {
                                return
                            }
							let flag = this.currentUser.loginId === this.Common.admin ||
									   this.currentUser.userId === params.row.createUserId  ||
									   this.currentUser.userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') != undefined ||
									   this.currentUser.userBeHandedOver.find(obj => obj == params.row.createUserId) != undefined
                            return h('div', [
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                    },
                                    on: {
                                        click: () => {
                                            this.InputData = JSON.parse(JSON.stringify(params.row));
                                            this.model3 = true;
                                        }
                                    }
                                }, '详情'), h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
										color:flag?'':'#c5c8ce',
										pointerEvents:flag?'':'none'
                                    },
                                    on: {
                                        click: () => {

                                            this.InputData = JSON.parse(JSON.stringify(params.row));
                                            this.model1 = true;
                                            this.add = false
                                        }
                                    }
                                }, '修改'), h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'error',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                        color:flag?'red':'#c5c8ce',
                                        pointerEvents:flag?'':'none'
                                    },
                                    on: {
                                        click: () => {

                                            this.$Modal.confirm({
                                                title: '提示',
                                                content: '<p>是否要删除？</p>',
                                                onOk: () =>{
                                                    this.deleteData(params.row);
                                                } ,
                                                onCancel: () => {
                                                }
                                            });
                                        }
                                    }
                                }, '删除')
                            ]);
                        }
                    }
                ],
                add: false,
                InputData: {deptLeaderId: '', deptLeaderName: ''},
                buttonLoading: false,
                switchFlag:false,
                model2: false,
                model1: false,
                model3: false,
                dictMap:{},
                columnsItem: [
                    // {title: '序号', width: 70, align: 'center', render: this.indexColumnsRender},
                    {title: '伤亡人员姓名', align: 'center', key: 'victim', minWidth: 100,},
                    {title: '性别', align: 'center', key: 'gender', minWidth: 80,render: (h, params) => {
                            return h('span', params.row.gender == '0' ? '男' : '女')}},
                    {title: '年龄', align: 'center', key: 'age', minWidth: 80,},
                    {title: '工种或岗位', align: 'center', key: 'position', minWidth: 120,},
                    {title: '伤害部位', align: 'center', key: 'injured', minWidth: 120,},
                    {title: '就业类型', align: 'center', key: 'membershipName', minWidth: 120,},
                    {title: '伤害程度', align: 'center', key: 'injuryLevelName', minWidth: 120,},
                    {title: '歇工天数', align: 'center', key: 'daysWork', minWidth: 100,},
                    {title: '直接经济损失(万元)', align: 'center', key: 'loseMoney', minWidth: 120,},
                ],
            }
        },
        mounted() {
            this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 193;
          this.selectCodingSort();
            this.query()

        },
        methods: {
            openForSelect() {
                this.briefingList = true;
            },
            switchQuery(flag) {
                this.switchFlag = flag;
                if (!this.switchFlag) {
                    this.tableHeight = this.tableHeight + 44;
                } else {
                    this.tableHeight = this.tableHeight - 44;
                }
            },
            getSelectData(row) {
                this.InputData.accTypeName = row.accTypeName
                this.InputData.accTypeId = row.accTypeId
                this.InputData.sartName = row.sartName;
                this.InputData.briefId = row.briefId;
                this.InputData.victim = row.victim;
                this.InputData.damage = row.loseMoney;
                this.InputData.briefItems = row.briefItems;
                // this.InputData.employmentType = row.membershipId;
                // this.InputData.employmentTypeName = row.membershipName;
                // this.InputData.injuryLevelName = row.injuryLevelName;
                this.briefingList = false;
            },



            onCancel() {
                this.InputData = {}
                this.model1 = false
                this.model3 = false
                this.query();

            },
            submit(name) {
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        this.buttonLoading = true
                        if (this.add) {
                            let url = Api.follow
                            this.InputData.bsflag = '0'
                            this.InputData.createOrgId = sessionStorage('userId').getObject('userId').orgInfo.orgId
                            this.InputData.createUserId = sessionStorage('userId').getObject('userId').userId
                            this.$http.post(url, this.InputData).then((res) => {
                                this.$Message.success('成功');
                                this.query()
                                this.buttonLoading = false
                                this.model1 = false
                            }).catch(e => {
                                this.$Message.error('请求失败');
                            })
                        } else {
                            let url = Api.follow;
                            this.InputData.updateUserId = sessionStorage('userId').getObject('userId').userId
                            this.InputData.updateOrgId = sessionStorage('userId').getObject('userId').orgInfo.orgId
                            this.$http.put(url, this.InputData).then((res) => {
                                this.$Message.success('成功');
                                this.buttonLoading = false
                                this.model1 = false
                                this.query()
                            }).catch(e => {
                                this.$Message.error('请求失败');
                            })
                        }
                    } else {
                        this.$Message.error('请填报完整!');
                    }
                })

            },
            selectCodingSort() {
                // this.$http.get(Api.queryCodeDetailBySortId + '/MEM-000001', {params: {}}).then((res) => {
                //     this.membershipList = res.data.data;
                // });
                // this.$http.get(Api.queryCodeDetailBySortId + '/TG-000001', {params: {}}).then((res) => {
                //     this.locationSurveyList = res.data.data;
                // });
                // this.$http.get(Api.queryCodeDetailBySortId + '/FM-000001', {params: {}}).then((res) => {
                //     this.appesaseList = res.data.data;
                // });
                // this.$http.get(Api.queryCodeDetailBySortId + '/1000001019', {params: {}}).then((res) => {
                //     this.injuryLeveList = res.data.data;
                // });

                this.$http.get(Api.queryDictBycode+"ACC-000001",{}).then((res)=>{
                    this.dictMap = {
                        'typeList': res.data.data['ACC-000001'],
                    }
                }).catch(e => {
                    this.$Message.error("数据字典获取失败")
                });

            },

            deleteData(row) {
                let url = Api.follow
                let data = {
                    fReportId: row.fReportId
                };
                this.$http.delete(url, {params: data}).then((res) => {
                    this.$Message.success('成功');
                    this.query()
                }).catch(e => {
                    this.$Message.error("数据获取失败")
                })
            },
            addInfo() {
                let userId = sessionStorage('userId').getObject('userId').userId;
                let userName = sessionStorage('userId').getObject('userId').userName;
                this.uploadList = [];
                this.add = true;
                this.InputData = {
                    deptLeaderId: userId,
                    deptLeaderName: userName,
                    damage:0,
                };
                this.model1 = true;
            },
            query() {
                let data = {
                    starPage: this.pagedata.currentPage,
                    size: this.pagedata.pageSize,
                    // orgId: sessionStorage('userId').getObject('userId').companyId
                };

                data = Object.assign(data, JSON.parse(JSON.stringify(this.form1)));

                let url = Api.follow
                this.loading = true;
                this.$http.get(url, {params: data}).then((res) => {
                    console.log(res.data);
                    this.dataTable = res.data.data.data;
                    this.pagedata.total = res.data.data.totalSize;
                    this.loading = false;
                }).catch(e => {
                    this.$Message.error("数据获取失败")
                })
            },
            reset() {
                this.form1 = {};
                this.pagedata.currentPage = 1;
                this.query();
            },

            pageChange(pageNum) {
                this.pagedata.currentPage = pageNum;
                this.query();
            },
            pageSizeChange(pageSize) {
                this.pagedata.pageSize = pageSize;
                this.query();
            },
			formatDate(date, fmt) {
				if(!(date instanceof Date)) return date;
			    if (/(y+)/.test(fmt)) {
			        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
			    }
			    let o = {
			        'M+': date.getMonth() + 1,
			        'd+': date.getDate(),
			        'h+': date.getHours(),
			        'm+': date.getMinutes(),
			        's+': date.getSeconds()
			    };
			    for (let k in o) {
			        if (new RegExp(`(${k})`).test(fmt)) {
			            let str = o[k] + '';
			            fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : ( ('00' + str).substr(str.length)));
			        }
			    }
			    return fmt;
			},
            get_uuid() {
                let s = [];
                let hexDigits = "0123456789abcdef";
                for (let i = 0; i < 36; i++) {
                    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
                }
                s[14] = "4";
                s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
                s[8] = s[13] = s[18] = s[23] = "-";

                let uuid = s.join("");
                let reg = new RegExp("-", "g");
                let a = uuid.replace(reg, "");
                console.log(a);
                return a;
            },

        },
        watch: {

        },
    }
</script>

<style scoped>
    @import '../../../../index.css';

</style>
